import {
	jsonString
} from "../uni_modules/wu-ui-tools/libs/function/test";


class WebSocketClient {

	constructor(url,authorization) {
		this.url = url;
		this.authorization = authorization;
		this.heartbeatInterval = 240000; // 心跳间隔时间（毫秒）
		this.heartbeatTimeout = 10000; // 心跳超时时间（毫秒）
		this.reconnectTimeout = 10000; // 重连间隔时间（毫秒）
		this.heartbeatTimer = null;
		this.reconnectTimer = null;
		this.ws = null;
		this.isopenSocket = false;
		this.connectCount = 0;
		this.sendData = null;
	}

	connect() {
		
		return new Promise((resolve, reject) => {
			// console.log("authorization:",this.authorization);
			this.ws = uni.connectSocket({
				url: this.url,
				header: {
					'content-type': 'application/json',
					'Authorization': this.authorization
				},
				protocols: ['protocol1'],
				complete: (res) => {
					resolve();
					console.log("connect:", res);
				}
			});
			this.ws.onOpen(() => {
				console.log('WebSocket连接已打开');
				if(this.sendData){
					this.ws.send({
						data: JSON.stringify(this.sendData),
						success: (res) => {
							console.log("发送success:", this.sendData);
						},
						fail: (err) => {
							console.log("发送fail:", err);
						}
					});
				}
				this.isopenSocket = true;
				resolve();
				this.startHeartbeat();
				
			});
			
			this.ws.onMessage((message) => {
				// console.log('收到服务器消息websocket:', message.data);
				this.startHeartbeat();
			});

			this.ws.onError((error) => {
				this.isopenSocket = false;
				console.error('WebSocket连接发生错误:', error);
				reject(error);
				this.clearHeartbeatTimeout();
				this.reconnect();
				
			});

			this.ws.onClose((err) => {
				reject(false);
				console.log('WebSocket连接已关闭', err);
				this.clearHeartbeatTimeout();
				this.isopenSocket = false;
				this.reconnect();
			});

		});


	}


	startHeartbeat() {
		this.clearHeartbeatTimeout();
		this.heartbeatTimer = setInterval(() => {
			this.ws.send({
				data: JSON.stringify({
					type: 99
				}),
				success: () => {
					console.log("heart beat success")
				},
				fail: () => {

				}
			});
		}, this.heartbeatInterval);

		
	}

	clearHeartbeatTimeout() {
		clearInterval(this.heartbeatTimer);
		clearTimeout(this.heartbeatTimeoutTimer);
		clearTimeout(this.reconnectTimer);
	}

	reconnect() {
		this.connectCount ++;
		if(this.connectCount == 10){
			console.log("返回退出");
			this.ws.close();
			this.ws == null;
		
			return;
		}
		if(this.reconnectTimer){
			return;
		}
		this.reconnectTimer = setTimeout(() => {
			clearTimeout(this.reconnectTimer);
			this.reconnectTimer = null;
			this.connect();

		}, this.reconnectTimeout);
	}
	
	//发送消息
	sendMessage(data) {
		const user = uni.getStorageSync('user');
		data.userId = user.userId;
		this.sendData = data;
		if(this.isopenSocket){
			this.ws.send({
				data: JSON.stringify(data),
				success: (res) => {
					console.log("发送success:", data);
				},
				fail: (err) => {
					console.log("发送fail:", err);
				}
			});
		}
		else{
			this.reconnect();
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.ws.onMessage((res) => {
			this.startHeartbeat();
			// console.log('websocket:', res.data);
			return callback(res)
		})
	}	
}

export default WebSocketClient